<?php
namespace app\Tool\zq;

use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
use think\facade\Config;

class Es
{
    private $client;
    public $index_name;

    public function __construct()
    {
        try{
            //加载配置文件
			$params = config::get('es')['host'];
            //构建客户端对象
            $this->client = ClientBuilder::create()->setHosts($params)->build();
        }catch (\Exception $e){
            throw $e;
        }
    }

    // 创建索引
    public function create_index($index_name = 'keywords') { // 只能创建一次
        $params = [
            'index' => $index_name,
            'body' => [
                'settings' => [
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0
                ]
            ]
        ];

        try {
            return $this->client->indices()->create($params);
        } catch (Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    // 删除索引
    public function delete_index($index_name = 'keywords') {
        $params = ['index' => $index_name];
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    // 创建文档模板
    public function create_mappings($index_name = 'keywords') {

        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            'body' => [
				'properties' => [
					'name' => [				// 关键词
						'type' => 'text', // 字符串型
						'index' => 'true', 	// 全文搜索
					],
					'ip' => [				// ip
						'type' => 'text', 
						'index' => 'true',
					],
					'province' => [				// ip
						'type' => 'text', 
						'index' => 'true',
					],
					'city' => [				// ip
						'type' => 'text', 
						'index' => 'true',
					],
					'county' => [				// ip
						'type' => 'text', 
						'index' => 'true',
					],
					'time' => [				// ip
						'type' => 'date', 
						'index' => 'true',
					],
					
				]
            ]
        ];

        $response = $this->client->indices()->putMapping($params);
        return $response;
    }

    // 查看映射
    public function get_mapping($index_name = 'keywords') {
        $params = [
            'index' => $index_name,
            // 'type' => $type_name
        ];
        $response = $this->client->indices()->getMapping($params);
        return $response;
    }

    // 添加文档
    public function add_doc($id,$doc,$index_name = 'keywords') {
        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            // 'id' => $id,
            'body' => $doc
        ];

        $response = $this->client->index($params);
        return $response;
    }

    // 判断文档存在
    public function exists_doc($id = 1,$index_name = 'keywords') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->exists($params);
        return $response;
    }


    // 获取文档
    public function get_doc($id = 1,$index_name = 'keywords') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->get($params);
        return $response;
    }

    // 更新文档
    public function update_doc($id = 1,$index_name = 'keywords') {
        // 可以灵活添加新字段,最好不要乱添加
        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            'id' => $id,
            'body' => [
                'doc' => [
                    'title' => '苹果手机iPhoneX'
                ]
            ]
        ];

        $response = $this->client->update($params);
        return $response;
    }

    // 删除文档
    public function delete_doc($id = 1,$index_name = 'keywords') {
        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->delete($params);
        return $response;
    }

    // 查询文档 (分页，排序，权重，过滤)
    public function search_doc($query ,$from = 0,$size = 10,$index_name = "keywords") {
        $keywords = '*美*';
        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            'body' => [
                // 'query' => [
                //     'bool' => [
                //         'should' => [
                //             [ 'match' => [ 'name' => [
                //                 'query' => $keywords,
                //                 'boost' => 3, // 权重大
                //             ]]],
                //             [ 'match' => [ 'ip' => [
                //                 'query' => $keywords,
                //                 'boost' => 2,
                //             ]]],
                //         ],
                //     ],
                // ],
                // 'query' => [
                //     'bool' => [
                //         'should' =>$query
                //     ],
                // ],
                'query' => $query,
                // 'sort' => ['price'=>['order'=>'desc']], 
                'from' => $from, 'size' => $size
            ]
        ];
        $results = $this->client->search($params);
//        $maxScore  = $results['hits']['max_score'];
//        $score = $results['hits']['hits'][0]['_score'];
//        $doc   = $results['hits']['hits'][0]['_source'];
        return $results['hits'];
    }
	
	// 查询文档 (分页，排序，权重，过滤)
    public function search_all($from = 0,$size = 2,$index_name = "keywords") {
        $params = [
            'index' => $index_name,
            // 'type' => $type_name,
            'body' => [
                'from' => $from, 'size' => $size
            ]
        ];
        $results = $this->client->search($params);
        return $results;
    }
	
	
	
}